package gov.fema.hazus.bdc.server.servlet;

import gov.fema.hazus.bdc.shared.entity.Address;
import gov.fema.hazus.bdc.shared.entity.Building;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.cache.Cache;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.appengine.api.datastore.FetchOptions;
import com.googlecode.objectify.OQuery;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class SearchRangeBuildingsObjectify extends HttpServlet {

	private static final long serialVersionUID = 7621548404917186180L;

	public static final String TASK_PATH = "/task/objectify/buildings/range";

	private final Logger logger = Logger.getLogger(SearchRangeBuildingsObjectify.class);

    private DAO dao = new DAO();
    
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	 throws ServletException, IOException {
			
		doGet(req, resp);
		
	 }
	
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws IOException {
        
    	res.setContentType("text/plain");
		String searchTerm = req.getParameter("q");
		
		String limit = req.getParameter("limit");
		if( limit == null )
		{
			limit = "1000";
		}
		String offset = req.getParameter("offset");
		if( offset == null )
		{
			offset = "0";
		}
		int limitInt = Integer.parseInt(limit);
		int offsetInt = Integer.parseInt(offset);
		
		try {
			
			Objectify ofy = ObjectifyService.begin();
			OQuery<Building> q = ObjectifyService.createQuery(Building.class);
			q.filter("terms == ", searchTerm.toUpperCase());
			List<Building> buildings = ofy.prepare(q).asList(FetchOptions.Builder.withLimit(limitInt).offset(offsetInt));
			for (Iterator iterator = buildings.iterator(); iterator.hasNext();) {
				Building building = (Building) iterator.next();
				res.getWriter().println(building.toString());
			    logger.debug(building.toString());
			}
			/*
			for (Building building: ofy.prepare(q).asList()) {
				
				// now that we have the ID, fetch the other entities
				Address address = ofy.get(Address.class, building.getId());
				logger.debug(address.toString());
				building.setAddress(address);
				
				res.getWriter().println(building.toString());
			    logger.debug(building.toString());
			}*/
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    }
	
}
